package io.lckgroup.modules.lck.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.lckgroup.common.utils.PageUtils;
import io.lckgroup.common.utils.Query;
import io.lckgroup.modules.lck.dao.ShopFoodAuditDao;
import io.lckgroup.modules.lck.dao.ShopFoodDao;
import io.lckgroup.modules.lck.dao.ShopFoodSpecDao;
import io.lckgroup.modules.lck.dao.ShopFoodTypeDao;
import io.lckgroup.modules.lck.entity.*;
import io.lckgroup.modules.lck.entity.appvo.ShopFoodEntityVo;
import io.lckgroup.modules.lck.entity.wxmpvo.ShopFoodEntityWeixinVo;
import io.lckgroup.modules.lck.entity.wxmpvo.ShopFoodSpecEntityWeixinVo;
import io.lckgroup.modules.lck.form.ShopFoodEntityForm;
import io.lckgroup.modules.lck.form.wxgzh.ShopFoodEntityWxgzhForm;
import io.lckgroup.modules.lck.form.wxgzh.ShopFoodWxgzhForm;
import io.lckgroup.modules.lck.service.ShopFoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("shopFoodService")
public class ShopFoodServiceImpl extends ServiceImpl<ShopFoodDao, ShopFoodEntity> implements ShopFoodService {

    //菜品表
    @Autowired
    private ShopFoodDao shopFoodDao;

    @Autowired
    private ShopFoodSpecDao shopFoodSpecDao;

    @Autowired
    private ShopFoodTypeDao shopFoodTypeDao;

    @Autowired
    private ShopFoodAuditDao shopFoodAuditDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ShopFoodEntity> page = this.page(
                new Query<ShopFoodEntity>().getPage(params),
                new QueryWrapper<ShopFoodEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByEntity(Map<String, Object> params, ShopFoodEntity shopFoodEntity) {

        IPage<ShopFoodEntity> page = this.page(
                new Query<ShopFoodEntity>().getPage(params, "is_upper", false),
                new QueryWrapper<ShopFoodEntity>(shopFoodEntity)
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    @CacheEvict(value = {"findFoodList", "selectPageByAuditState"}, allEntries = true)
    public boolean myAddOrUpdate(ShopFoodEntityForm entity) {

        boolean result = true;
        if (null == entity.getId()) {

            //entity.setGmtCreate(new Date());
            //新增数据
            int insert = shopFoodDao.insert(entity);

            if (insert != 0) {//新增规格数据
                //修改菜品分类的菜品数量
                ShopFoodTypeEntity sft = new ShopFoodTypeEntity();
                sft.setId(Long.parseLong(entity.getGoodsTypeId().toString()));
                ShopFoodTypeEntity osft = shopFoodTypeDao.selectById(entity.getGoodsTypeId());
                sft.setFoodNum(osft.getFoodNum() + 1);
                shopFoodTypeDao.updateById(sft);
                List<ShopFoodSpecEntity> list = entity.getShopFoodSpecs();
                if (null != list && list.size() > 0) {
                    for (ShopFoodSpecEntity item : list) {
                        if (null == item.getId()) {
                            item.setGoodsId(entity.getId());
                            //item.setGmtCreate(new Date());
                        }
                        int i = shopFoodSpecDao.insert(item);
                        if (0 == i) {
                            result = false;
                        }
                    }
                }
            } else {
                result = false;
            }
        } else {//执行修改方法
            //entity.setGmtModified(new Date());
            //修改之前的数据
            ShopFoodEntity last = shopFoodDao.selectById(entity.getId());
            int update = shopFoodDao.updateById(entity);
            if (update != 0) {
                if (last.getGoodsTypeId().compareTo(entity.getGoodsTypeId()) != 0) {//修改了类型
                    //原来类型减一
                    ShopFoodTypeEntity lastType = shopFoodTypeDao.selectById(last.getGoodsTypeId());
                    lastType.getFoodNum();
                    ShopFoodTypeEntity sft = new ShopFoodTypeEntity();
                    sft.setId(lastType.getId());
                    if (lastType.getFoodNum() - 1 <= 0) {
                        sft.setFoodNum(0);
                    } else {
                        sft.setFoodNum(lastType.getFoodNum() - 1);
                    }
                    shopFoodTypeDao.updateById(sft);
                    //新的类型加一
                    ShopFoodTypeEntity osft = shopFoodTypeDao.selectById(entity.getGoodsTypeId());
                    sft = new ShopFoodTypeEntity();
                    sft.setId(osft.getId());
                    sft.setFoodNum(osft.getFoodNum() + 1);
                    shopFoodTypeDao.updateById(sft);
                }
                //先删除原有的菜品规格
                ShopFoodSpecEntity spc = new ShopFoodSpecEntity();
                spc.setGoodsId(entity.getId());
                Wrapper<ShopFoodSpecEntity> queryWrapper = new QueryWrapper<ShopFoodSpecEntity>(spc);
                //shopFoodSpecService.remove(queryWrapper);
                shopFoodSpecDao.delete(queryWrapper);
                //新增菜品规格
                List<ShopFoodSpecEntity> list = entity.getShopFoodSpecs();
                if (null != list && list.size() > 0) {
                    for (ShopFoodSpecEntity item : list) {
                        if (null == item.getId()) {
                            item.setGoodsId(entity.getId());
                            //item.setGmtCreate(new Date());
                        }
                        //shopFoodSpecService.save(item);
                        int i2 = shopFoodSpecDao.insert(item);
                        if (0 == i2) {
                            result = false;
                        }
                    }
                }
            } else {
                result = false;
            }
        }

        //创建审核信息
        boolean am = this.mySaveAuditMsg(entity);
        if (!am) {
            result = false;
        }
        return result;
    }

    @Transactional
    @Override
    @CacheEvict(value = {"findFoodList", "selectPageByAuditState"}, allEntries = true)
    public boolean myDeleteShopFoodById(Serializable id) {

        ShopFoodEntity entity = shopFoodDao.selectById(id);
        ShopFoodTypeEntity typeEntity = shopFoodTypeDao.selectById(entity.getGoodsTypeId());
        Integer foodNum = typeEntity.getFoodNum();
        ShopFoodTypeEntity n = new ShopFoodTypeEntity();
        n.setId(typeEntity.getId());
        if (foodNum - 1 < 0) {
            n.setFoodNum(0);
        } else {
            n.setFoodNum(foodNum - 1);
        }
        //修改分类下的菜品数量
        int r1 = shopFoodTypeDao.updateById(n);
        ShopFoodEntity se = new ShopFoodEntity();
        se.setId(Long.valueOf(id.toString()));
        se.setIsDelete(1);
        int r3 = shopFoodDao.updateById(se);
        return (r1 >= 0 && r3 >= 0) ? true : false;
    }

    /**
     * 添加审核信息
     *
     * @param entity
     * @return 成功：true；失败：false。
     */
    private boolean mySaveAuditMsg(ShopFoodEntity entity) {
        ShopFoodAuditEntity sfae = new ShopFoodAuditEntity();
        sfae.setMerchantId(entity.getMerchantId());
        sfae.setFoodId(entity.getId());
        sfae.setAuditState(0);
        //sfae.setGmtCreate(new Date());
        int i = shopFoodAuditDao.insert(sfae);
        return i > 0 ? true : false;
    }

    @Override
    public List getFoodList(Integer merchantId) {
        //根据商家id查出所有菜品类型和类型id
        QueryWrapper<ShopFoodTypeEntity> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("merchant_id", merchantId);
        List<ShopFoodTypeEntity> shopFoodTypeEntities = shopFoodTypeDao.selectList(queryWrapper1);
        //遍历 将菜品类型和对应菜品封装成map
        Map map;
        List<Object> list = new ArrayList<>();
        for (ShopFoodTypeEntity foodTypeEntity : shopFoodTypeEntities) {
            map = new HashMap<String, Object>();
            map.put("name", foodTypeEntity.getTypeName());

            QueryWrapper<ShopFoodEntity> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("food_type_id", foodTypeEntity.getId());
            queryWrapper2.eq("merchant_id", merchantId);
            queryWrapper2.eq("is_upper", 1);//上架的菜品
            queryWrapper2.eq("audit_state", 1);//审核通过
            //根据菜品类型id和商家id查出对应菜品
            List<ShopFoodEntity> shopFoodEntities = shopFoodDao.selectList(queryWrapper2);
            List<ShopFoodEntityWxgzhForm> shopFoodEntity_wxgzhForms = new ArrayList<>();
            //遍历菜品，查询规格
            for (ShopFoodEntity shopFoodEntity : shopFoodEntities) {
                if (shopFoodEntity.getIsSpecs() == 1) {//如果有规格
                    QueryWrapper<ShopFoodSpecEntity> queryWrapper3 = new QueryWrapper<>();
                    queryWrapper3.eq("food_id", shopFoodEntity.getId());
                    List<ShopFoodSpecEntity> ShopFoodSpecList = shopFoodSpecDao.selectList(queryWrapper3);
                    //遍历菜品规格list再次进行封装
                    for (ShopFoodSpecEntity shopFoodSpecEntity : ShopFoodSpecList) {
                        ShopFoodEntityWxgzhForm sw = new ShopFoodEntityWxgzhForm(shopFoodEntity);
                        sw.setFoodName(shopFoodEntity.getGoodsName() + "(" + shopFoodSpecEntity.getSpecsName() + ")");
                        sw.setPrice(shopFoodSpecEntity.getPrice());
                        sw.setSpecsName(shopFoodSpecEntity.getSpecsName());
                        sw.setSpecsId(shopFoodSpecEntity.getId());
                        shopFoodEntity_wxgzhForms.add(sw);
                    }
                } else {
                    ShopFoodEntityWxgzhForm sw = new ShopFoodEntityWxgzhForm(shopFoodEntity);
                    shopFoodEntity_wxgzhForms.add(sw);
                }
            }

            map.put("foods", shopFoodEntity_wxgzhForms);
            list.add(map);
        }
        return list;
    }

    @Override
    public PageUtils queryByPage(Map<String, Object> params) {
//        IPage<ShopFoodEntity> page = this.page(
//                new Query<ShopFoodEntity>().getPage(params),
//                new QueryWrapper<ShopFoodEntity>().eq("audit_state", 1).eq("is_upper", 1)
//        );
//        return new PageUtils(page);
        //分页参数
        Page page = new Page<>(Integer.valueOf(params.get("page").toString()), Integer.valueOf(params.get("limit").toString()));
        IPage<ShopFoodWxgzhForm> iPage = shopFoodDao.queryByPage(page);
        return new PageUtils(iPage);
    }

    /**
     * 功能描述: <br>
     * 〈〉获取商品集合
     *
     * @Param: []
     * @Return: java.util.List
     * @Author: 13980
     * @Date: 2020/3/3 15:30
     */
    @Override
    @Cacheable(value = "findFoodList", key = "#ShopMerchantInId")
    public List findFoodList(Long ShopMerchantInId) {

        ShopFoodTypeEntity shopFoodTypeEntity = new ShopFoodTypeEntity();
//某一菜品类型和相应菜品的map
        Map typeName;
        List<Object> list = new ArrayList<>();
        //        查询所有菜品类型
        QueryWrapper<ShopFoodTypeEntity> wrapper1 = new QueryWrapper<>();
//        菜品类型  商家ID
        shopFoodTypeEntity.setMerchantId(ShopMerchantInId);
        wrapper1.setEntity(shopFoodTypeEntity);
        List<ShopFoodTypeEntity> shopFoodTypeEntities = shopFoodTypeDao.selectList(wrapper1);
//        便利菜品类型
        QueryWrapper<ShopFoodEntity> wrapper3 = new QueryWrapper<>();
        ShopFoodEntity temp = new ShopFoodEntity();
        for (ShopFoodTypeEntity foodTypeEntity : shopFoodTypeEntities) {
            typeName = new HashMap<String, Object>();
//            把对应菜品和菜品类型封装成一个map
            typeName.put("typeName", foodTypeEntity.getTypeName());
            temp.setGoodsTypeId(foodTypeEntity.getId());
//            只查询上架的菜品
            temp.setIsUpper(1);
//            软删除  0未删除
            temp.setIsDelete(0);
//            商家ID
            temp.setMerchantId(ShopMerchantInId);
            wrapper3.setEntity(temp);
//            根据每一个菜品类型查询出来的菜品集合
            List<ShopFoodEntity> shopFoodEntities = shopFoodDao.selectList(wrapper3);
//            返回给前端封装过的菜品类型集合
            List<ShopFoodEntityWeixinVo> shopFoodEntity_weixin_vosList = new ArrayList<>();
//            便利集合，若菜品有规格则加入规格
            for (ShopFoodEntity foodEntity : shopFoodEntities) {
                ShopFoodEntityWeixinVo vo = null;
                // 有规格
                if (foodEntity.getIsSpecs() == 1) {
                    QueryWrapper<ShopFoodSpecEntity> ShopFoodSpecEntityWrapper = new QueryWrapper<>();
                    ShopFoodSpecEntity entity = new ShopFoodSpecEntity();
                    entity.setGoodsId(foodEntity.getId());
                    ShopFoodSpecEntityWrapper.setEntity(entity);
                    List<ShopFoodSpecEntity> ShopFoodSpecList = shopFoodSpecDao.selectList(ShopFoodSpecEntityWrapper);
                    List<ShopFoodSpecEntityWeixinVo> specEntityList = new ArrayList<>();
                    for (ShopFoodSpecEntity specEntity : ShopFoodSpecList) {
                        ShopFoodSpecEntityWeixinVo weixin_vo = new ShopFoodSpecEntityWeixinVo(specEntity);
                        specEntityList.add(weixin_vo);
                    }
                    vo = new ShopFoodEntityWeixinVo(specEntityList, foodEntity);
                } else {
                    vo = new ShopFoodEntityWeixinVo(foodEntity);
                }
                shopFoodEntity_weixin_vosList.add(vo);
            }
            //            把菜品装进去，成为一个对象
            typeName.put("foodList", shopFoodEntity_weixin_vosList);

            list.add(typeName);
        }
        return list;
    }


    @Override
    public IPage<ShopFoodEntityVo> queryPageByDefine(Map<String, Object> params) {
        Page<Map<String, Object>> page =
                new Page<>(Integer.parseInt(params.get("page").toString()),
                        Integer.valueOf(params.get("limit").toString()));
        IPage<ShopFoodEntityVo> r = shopFoodDao.queryPageByDefine(page, params);
        return r;
    }
}